/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package coalescent.cef.command;

import cef.command.CommandException;
import coalescent.cef.event.MLE_KC64ThetaEvent;
import coalescent.model.K69;
import coalescent.recursion.ProbComputer_Exact_Multi;
import coalescent.recursion.Recursion;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version version
 * @user Susanta Tewari
 * @history First created on 10/22/12.
 * @since 1.4.0
 */
public final class MLE_K69ThetaCommand extends MLE_KC64ThetaCommand {

    public MLE_K69ThetaCommand(final MLE_KC64ThetaEvent event) {
        super(event);
    }

    @Override
    public void executeImpl() throws CommandException, InterruptedException {

        final MLE_KC64ThetaEvent evt = getEvent();


        // models
        final List<Double> thetas = thetaValues(evt.getThetaMin(), evt.getThetaMax(),
                                        evt.getThetaIncrement());
        final List<K69> models = new ArrayList<>(thetas.size());

        for (final double theta : thetas) {
            models.add(new K69(theta));
        }


        // recursion
        final Recursion recursion                        = new Recursion(evt.getStatistic());
        final ProbComputer_Exact_Multi<K69> probComputer = new ProbComputer_Exact_Multi<>(models);

        recursion.addExactRecursionEventListener(probComputer);
        recursion.runRecursion();


        // collect theta-probs
        thetaProbabilities = new HashMap<>(thetas.size());

        final Map<K69, BigDecimal> prob_map = probComputer.getResult();

        for (final K69 model : prob_map.keySet()) {
            thetaProbabilities.put(model.getMutationRate(), prob_map.get(model));
        }

        setCmdFinished(true);
        fireOutputEvent(getOutputEvent());
    }

    public static boolean isCancellable() {
        return true;
    }
}
